--EXEC Sp_Get_Periodo_NewId @cPerJurCodigo='9000013375'

-- =============================================
-- AUTOR:	Oscar Gomez Sanchez
-- FECHA:	27/09/2013
-- Description:	Crear Nuevo nPrdCodigo
-- =============================================


CREATE PROCEDURE [dbo].[Sp_Get_Periodo_NewId]
	@cPerJurCodigo Char(10) = null
AS
BEGIN
	DECLARE @nPrdCodigo int 

	SET NOCOUNT ON;

	IF ISNULL(@cPerJurCodigo,'') = '' 
		SELECT @nPrdCodigo = ISNULL(MAX(nPrdCodigo),0) + 1 
		FROM Periodo with (nolock)
	ELSE
		BEGIN
			DECLARE @Rango nVarChar(20)
		
			SELECT top 1 @Rango = ISNULL(cPerIdeNumero, '0') 
			FROM PerIdentifica  with (nolock)
			WHERE cPerCodigo = @cPerJurCodigo 
			AND nPerIdeTipo  = 90000
		
			SELECT @nPrdCodigo = ISNULL(MAX(nPrdCodigo),0) + 1 
			FROM Periodo with (nolock)
			WHERE nPrdCodigo LIKE '' + @Rango + '%'

			IF @nPrdCodigo <=  1000000 
				SET @nPrdCodigo = CAST(ISNULL(@Rango,0) as Int) * 1000000
			
			IF @nPrdCodigo = 0 
				SELECT @nPrdCodigo = ISNULL(MAX(nPrdCodigo),0) + 1 
				FROM Periodo with (nolock)
		END

	SELECT @nPrdCodigo as nPrdCodigo
END





